<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class AddressTranslator 
{
	private $toolbox;

	public function __construct() {
		$this->toolbox = new Toolbox();
	}

	public function set_toolbox($toolbox) {
		$this->toolbox = $toolbox;
	}

	public function translate_addresses_to_db_keys($keyed_addresses, $internal_mail) {
		if (!$keyed_addresses) { 
			$nicks = $this->toolbox->get_keyed_values("user_id", "nick", "MEMBER");
			$nicks = array_map("strtolower", $nicks);
			$nicks = array_flip($nicks);
			$internal_mail->set_to_keys($this->translate_address_string_to_db_keys($internal_mail->get_to_addresses(), $nicks));
			$internal_mail->set_cc_keys($this->translate_address_string_to_db_keys($internal_mail->get_cc_addresses(), $nicks));
		} else {
			$internal_mail->set_to_keys(split('[,;]', ereg_replace(" ", "", $internal_mail->to)));
			if ($internal_mail->cc) {
				$internal_mail->set_cc_keys(split('[,;]', ereg_replace(" ", "", $internal_mail->cc)));
			}
		}
	}

	private function translate_address_string_to_db_keys($key_input, $nicks) {
		global $CONFIG;

		$addresses = split('[,;]', ereg_replace(" ", "", strip_tags($key_input)));
		$keys = array();
		while ($nick = array_pop($addresses)) {
			$lower_case_name = strtolower($nick);
			$key = $nicks[$lower_case_name];
			if (!$key) {
				throw new MailException("'{$nick}' is geen bekende gebruiker.");
			}
			if ($key == $CONFIG['system_user']) {
				throw new MailException("De systeemaccount ontvangt geen mail.");
			} 
			$keys[] = $key;
		}
		return $keys;
	}
}

?>
